// resolve reject 更改状态的标记
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失败
class MyPromise {
    // executor立即执行器
    constructor (executor) {
        //捕获错误
        try {
            executor(this.resolve, this.reject)
        } catch(e) {
            this.reject(e)
        }
        
    }
    //promise  状态
    status = PENDING
    // 成功之后的值
    value = undefined
    // 失败后的原因
    reason = undefined
    // 成功回调
    successCallback = []
    // 失败回调
    failCallback = []
    resolve = () => {
        // 如果状态不是等待，阻止程序向下执行
        if(this.status !== PENDING) return
        //将状态更改为成功
        this.status = FULFILLED
        // 保存成功之后的值
        this.value = this.value
        // 判断成功回调是否存在，如果存在调用
        // this.successCallback && this.successCallback(this.value) //  单个成功回调函数
        while(this.successCallback.length)  this.successCallback.shift()() //shift从前往后执行
    }
    reject = () => {
         // 如果状态不是等待，阻止程序向下执行
         if(this.status !== PENDING) return
        //将状态更改为失败
        this.status = REJECTED
        // 保存失败后的值
        this.reason = this.reason
         // 判断失败回调是否存在，如果存在调用
        //  this.failCallback && this.failCallback(this.reason) //单个失败函数
        while(this.failCallback.length )this.failCallback.shift()()
    }
    then(successCallback, failCallback) {
        //判断成功回调successCallback 是否存在，如果存在返回successCallback，如果不存在重新补充一个函数
        successCallback =  successCallback ? successCallback : value => value
        failCallback = failCallback ? failCallback : reason => {throw reason}
        // 每个then必须返回一个promise对象,才能链式操作,resolve传递给下一个promise对象
        let promise2 = new MyPromise( (resolve, reject) => {
            //判断状态
            if(this.status === FULFILLED) {
                // 把同步代码变成异步代码，能够拿到promise2
                setTimeout( () => {
                    // 拿到then成功回调的的返回值
                    // 判断x 的值时普通纸还是promise对象
                    // 如果promise对象，查看promise对象返回的结果，再根据promise对象返回的结果，决定调用resolve还是reject
                    try {
                        let x = successCallback(this.value)
                        // resolve(x)
                        // successCallback (this.value)
                        resolvePromise(promise2,x, resolve, reject)   
                    }catch(e) {
                        reject(e)
                    }
                 }, 0)
            } else if (this.status === REJECTED) {
                // failCallback(this.reason)
                setTimeout( () => {
                    try {
                        let x = failCallback(this.reason)
                        resolvePromise(promise2,x, resolve, reject)   
                    }catch(e) {
                        reject(e)
                    }
                 }, 0)
            } else {
                // 等待
                // this.status = PENDING
                // 将成功回调和失败回调存储起来
                this.successCallback.push(() => {
                    setTimeout( () => {
                        try {
                            let x = successCallback(this.value)
                            resolvePromise(promise2,x, resolve, reject)   
                        }catch(e) {
                            reject(e)
                        }
                     }, 0)
                })
                this.failCallback.push(() => {
                    setTimeout( () => {
                        try {
                            let x = failCallback(this.reason)
                            resolvePromise(promise2,x, resolve, reject)   
                        }catch(e) {
                            reject(e)
                        }
                     }, 0)
                })
            }
        })
        return promise2   
    }
    finally (callback) {
        return this.then( value => {
            return MyPromise.resolve(callback()).then(() => value)
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    catch(failCallback) {
       return this.then(undefined, failCallback)
    }
    //  声明all()为静态方法
    static all (array) {
        let result = [] 
        let index = 0
        return new MyPromise((resolve, reject) => {

            function addData(key, value) {
                result[key] = value
                index++
                if(index === array.length) {
                    console.log(result)
                    resolve(result)
                }
            }
            for(let i = 0;i < array.length; i++) {
                let current = array[i]
                if(current instanceof MyPromise) {
                    // promise 对象
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    //普通纸
                    addData(i, array[i])
                }
            }
        })
    }
    static resolve(value) {
        if(value instanceof MyPromise) return value
        return new MyPromise(resolve => this.resolve(value))
    }
    
}

function  resolvePromise(promise2, x, resolve, reject) {
    if(promise2 === x) {
        return reject(new TypeError('Chainin cycle detacted for pomise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        // promise 对象
        // x.then( (value) => {resolve(value)}, (reason) => {reject(reason)})
        x.then(resolve, reject)
    } else {
        //
        resolve(x)
    }
}

module.exports = MyPromise